package com.tianzehua.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;

/**
 * Grpc Server Bootstrap class
 * @author tianzehua
 * @date  2019/03/16
 */
public class GrpcServer {

    private Server server;

    /**
     *  定义启动服务器的方法
     * @throws Exception
     */
    private  void  start() throws Exception{
        this.server = ServerBuilder.forPort(8899).addService(new StudentsServiceImpl()).build().start();

        System.out.println("server start!");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("关闭jvm");
            GrpcServer.this.stop();
        }));
        System.out.println("执行到这里");
    }

    /**
     * 定义服务器关闭的方法
     */
    private  void stop() {
        if (this.server != null){
            this.server.shutdown();
        }
    }


    /**
     * 等待方法
     * @throws Exception
     */
    private void awaitTermination() throws Exception{
        if (this.server != null){
            this.server.awaitTermination();
        }
    }

    public static void main(String[] args)  throws Exception{
        GrpcServer server = new GrpcServer();

        server.start();
        server.awaitTermination();
    }


}
